﻿using System;
using System.Configuration;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Web.UI;
using CRMCommon;
using CRMCommon.DataSets;
using DevExpress.Web.ASPxClasses;

public partial class Customer : UserControl
{
    private readonly Controller _controller = new Controller();

    private void SetConnectionString()
    {
        _controller.SetupConnection(ConfigurationManager.AppSettings["FonteDados"], ConfigurationManager.AppSettings["NomeBaseDados"], 
            ConfigurationManager.AppSettings["User"], ConfigurationManager.AppSettings["Password"]);
    }

    private void LoadClient(long clientId)
    {
        SetConnectionString();
        ClienteDataSet clientData = _controller.GetClientById(clientId);
        CustomerNameTextBox.Text = clientData.Cliente[0].Nome;
        CustomerNIFTextBox.Text = clientData.Cliente[0].IsNumeroContribuinteNull() ? String.Empty : clientData.Cliente[0].NumeroContribuinte;
        ClientBinaryImage.ContentBytes = clientData.Cliente[0].IsFotografiaNull() ? GetDefaultImage() : clientData.Cliente[0].Fotografia;
        if (!clientData.Cliente[0].IsFotografiaNull())
            Session["ClientImage"] = clientData.Cliente[0].Fotografia;
        AddressMemoBox.Text = clientData.Cliente[0].IsMoradaNull() ? String.Empty : clientData.Cliente[0].Morada;
        PostalCodeTextBox.Text = clientData.Cliente[0].IsCodigoPostalNull() ? String.Empty : clientData.Cliente[0].CodigoPostal;
        TownTextBox.Text = clientData.Cliente[0].IsLocalidadeNull() ? String.Empty : clientData.Cliente[0].Localidade;
        CityTextBox.Text = clientData.Cliente[0].IsCidadeNull() ? String.Empty : clientData.Cliente[0].Cidade;
        DistrictTextBox.Text = clientData.Cliente[0].IsDistritoNull() ? String.Empty : clientData.Cliente[0].Distrito;
        TelephoneTextBox.Text = clientData.Cliente[0].IsTelefoneNull() ? String.Empty : clientData.Cliente[0].Telefone.ToString();
        EmailTextBox.Text = clientData.Cliente[0].IsEmailNull() ? String.Empty : clientData.Cliente[0].Email;
        ClientHiddenField["ClientId"] = clientId;
        ContactsGridView.DataSource = clientData.Contacto;
        ContactsGridView.DataBind();
    }

    private byte[] GetDefaultImage()
    {
        string imageUrl = "Images\\DefaultClient.gif";
        Image image = Image.FromFile(Server.MapPath(imageUrl));
        MemoryStream dataStream = new MemoryStream();
        image.Save(dataStream, ImageFormat.Gif);
        return dataStream.ToArray();
    }

    private ClienteDataSet BuildDataToSave(int clientId)
    {
        byte[] foto = Session["ClientImage"] == null ? null : (byte[])Session["ClientImage"];
        ClienteDataSet data = new ClienteDataSet();
        ClienteDataSet.ClienteRow client = data.Cliente.NewClienteRow();
        client.Id = clientId;
        client.Nome = CustomerNameTextBox.Text;
        client.Fotografia = foto;
        client.NumeroContribuinte = CustomerNIFTextBox.Text;
        client.Morada = AddressMemoBox.Text == String.Empty ? null : AddressMemoBox.Text;
        client.CodigoPostal = PostalCodeTextBox.Text == String.Empty ? null : PostalCodeTextBox.Text;
        client.Localidade = TownTextBox.Text == String.Empty ? null : TownTextBox.Text;
        client.Cidade = CityTextBox.Text == String.Empty ? null : CityTextBox.Text;
        client.Distrito = DistrictTextBox.Text == String.Empty ? null : DistrictTextBox.Text;
        if (TelephoneTextBox.Text != String.Empty)
            client.Telefone = Convert.ToInt64(TelephoneTextBox.Text);
        client.Email = EmailTextBox.Text == String.Empty ? null : EmailTextBox.Text;
        data.Cliente.AddClienteRow(client);
        return data;
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        SetConnectionString();
    }

    protected void CustomerCallbackPanel_Callback(object sender, CallbackEventArgsBase e)
    {
        long clientId;
        if(long.TryParse(e.Parameter, out clientId))
        {
            LoadClient(clientId);
            return;
        }
        if(e.Parameter.Equals("NewClient"))
        {
            ClientHiddenField.Remove("ClientId");
            Session.Remove("ClientImage");
            ClientBinaryImage.ContentBytes = GetDefaultImage();
            return;
        }
        if (e.Parameter.Equals(String.Empty))
        {
            if (!ClientHiddenField.Contains("ClientId") || ClientHiddenField["ClientId"] == null)
            {
                _controller.InsertClient(BuildDataToSave(-1).Cliente);
                Session.Remove("ClientImage");
            }
            else
            {
                _controller.UpdateClient(BuildDataToSave(Convert.ToInt16(ClientHiddenField["ClientId"])).Cliente);
                Session.Remove("ClientImage");
                ClientHiddenField.Remove("ClientId");
            }
        }
    }

    protected void ClientBinaryImageCallbackPanel_Callback(object sender, CallbackEventArgsBase e)
    {
        Bitmap objImage = new Bitmap(e.Parameter);
        MemoryStream stream = new MemoryStream();
        objImage.Save(stream, objImage.RawFormat);
        byte[] imageBytes = stream.ToArray();
        ClientBinaryImage.ContentBytes = imageBytes;
        Session["ClientImage"] = imageBytes;
    }
}
